<template>
    <div class="app-container">
        <el-form ref="adminInfo" :model="adminInfo" :rules="RegisterRules" label-width="120px" class="user-create-form">
            <el-form-item label="登录账号" prop="name">
                <el-input v-model="adminInfo.name" />
                <el-button type="primart" name="login" size="mini" @click="randomLogin()">随机登录账号</el-button>
            </el-form-item>
            <el-form-item label="账号密码" prop="password">
                <el-input v-model="adminInfo.password" />
                <el-button type="primart" name="password" size="mini" @click="randomPassword()">随机账号密码</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="createAdmn">确 定</el-button>
                <el-button @click="resetUser">取 消</el-button>
            </el-form-item>
        </el-form>

    </div>
</template>


<script>
import Admin from '@/api/admin.js'
import { uuid } from 'vue-uuid'
import { isvalidUsername } from '@/utils/validate'

export default {
    data() {
        const validateUsername = (rule, value, callback) => {
            if (!isvalidUsername(value)) {
                callback(new Error('请输入正确的用户名'))
            } else {
                callback()
            }
        }
        const validatePass = (rule, value, callback) => {
            if (value.length < 5) {
                callback(new Error('密码不能小于5位'))
            } else {
                callback()
            }
        }
        return {
            adminInfo: {
                name: '',
                password: '',
            },
            RegisterRules: {
                name: [{ required: true, trigger: 'blur', validator: validateUsername }],
                password: [{ required: true, trigger: 'blur', validator: validatePass }]
            },

        }
    },
    methods: {
        // 弹窗
        resetUser() {
            // 表单数据清空
            this.adminInfo.name = ''
            this.adminInfo.password = ''
        },
        // 随机账号
        randomLogin() {
            this.adminInfo.name = uuid.v1()
        },
        // 随机密码
        randomPassword() {
            this.adminInfo.password = uuid.v1()
        },
        // 增加新账号
        createAdmn() {
            this.$refs.adminInfo.validate(valid => {
                if (valid) {
                    Admin.createAdmin(this.adminInfo)
                        .then(() => {
                            this.dialogChapterFormVisible = false
                            this.$message({
                                type: 'success',
                                message: '添加管理员账号成功!'
                            })
                            this.$router.push({ path: '/user/list' })
                        }).catch(error => {
                        })
                }
            })
        }
    }
}
</script>
<style lang="scss">
.user-create-form {
    padding-left: 10%;
    padding-right: 10%;

}
</style>
